package com.zhoutao123.jsp;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.locks.LockSupport;


public class HelloWorldServlet extends HttpServlet {

  @Override
  public void init() throws ServletException {
    super.init();
    System.out.println("HelloWorldServlet.init");
  }

  @Override
  protected void service(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {
    super.service(req, resp);
    System.out.println("HelloWorldServlet.service");
  }

  @Override
  protected void doGet(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {
    resp.addHeader("Content-type", "text/html;charset=utf-8");
    resp.getOutputStream().write("人生若只如初见，何事悲风秋画扇".getBytes());
    resp.getOutputStream().flush();
  }

  @Override
  protected void doPost(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {
    super.doPost(req, resp);
  }

  @Override
  public void destroy() {
    super.destroy();
  }

  public static void main(String[] args) throws InterruptedException {
    String data = "1A2B3C4D5E6F7G8H9J0I";
    CountDownLatch latch = new CountDownLatch(1);
    Thread t1 =
        new Thread(
            () -> {
              try {
                latch.countDown();
                synchronized (HelloWorldServlet.class) {
                  for (int j = 0; j < data.length(); j += 2) {
                    System.out.print(data.charAt(j));
                    System.out.print(",");
                    HelloWorldServlet.class.notify();
                    HelloWorldServlet.class.wait();
                  }
                  HelloWorldServlet.class.notify();
                }
              } catch (InterruptedException e) {
                e.printStackTrace();
              }
            });

    new Thread(
            () -> {
              try {
                latch.await();
                synchronized (HelloWorldServlet.class) {
                  for (int i = 1; i < data.length(); i += 2) {
                    System.out.print(data.charAt(i));
                    System.out.print(",");
                    HelloWorldServlet.class.notify();
                    HelloWorldServlet.class.wait();
                  }
                  HelloWorldServlet.class.notify();
                }
              } catch (Exception e) {
                e.printStackTrace();
              }
            })
        .start();
    LockSupport.parkNanos(10000000);
    t1.start();
  }
}
